<template>
  <Dialog :title="t('student.interviewList.title')" v-model="dialogVisible" width="1400">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item :label="t('student.fields.studentName')" prop="studentName">
          <el-input
            v-model="queryParams.studentName"
            :placeholder="t('common.inputTextPlaceholder') + t('student.fields.studentName')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-160px"
          />
        </el-form-item>
        <el-form-item :label="t('student.fields.phone')" prop="phone">
          <el-input
            v-model="queryParams.phone"
            :placeholder="t('common.inputTextPlaceholder') + t('student.fields.phone')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-160px"
          />
        </el-form-item>
        <el-form-item :label="t('student.fields.interviewGroupId')" prop="interviewGroupId">
          <el-select
            v-model="queryParams.interviewGroupId"
            :placeholder="t('common.selectTextPlaceholder') + t('student.fields.interviewGroupId')"
            clearable
            class="!w-160px"
            @change="handleQuery"
          >
            <el-option
              v-for="item in groups"
              :key="item.id"
              :label="item.groupName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('student.fields.interviewSelected')" prop="interviewSelected">
          <el-select
            v-model="queryParams.interviewSelected"
            :placeholder="t('common.selectTextPlaceholder') + t('student.fields.interviewSelected')"
            clearable
            class="!w-160px"
            @change="handleQuery"
          >
            <el-option :label="t('common.yes')" :value="true" />
            <el-option :label="t('common.no')" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('student.interviewList.scoreGt')" prop="phone">
          <el-input-number
            v-model="queryParams.interviewScore"
            :placeholder="t('common.inputTextPlaceholder') + t('student.interviewList.scoreGt')"
            clearable
            @keyup.enter="handleQuery"
            class="better-number-input !w-160px"
            :controls="false"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px" /> {{ t('common.search') }}
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" /> {{ t('common.reset') }}
          </el-button>
          <el-button
            type="primary"
            plain
            @click="handleBatchSetInterviewResult"
            v-hasPermi="['recruit:student:update']"
            :disabled="selectListObject.length === 0"
          >
            <Icon icon="ep:finished" class="mr-5px" />
            {{ t('student.index.setResultBatch') }}
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <vxe-table
        ref="tableRef"
        v-loading="loading"
        :data="list"
        stripe
        :row-config="{ keyField: 'id' }"
        :checkbox-config="{
          reserve: true,
          checkMethod: ({ row }) => !!row.interviewScore
        }"
        :column-config="{ resizable: true }"
        :size="vxeTableSize"
        @checkbox-all="collectSelect"
        @checkbox-change="collectSelect"
      >
        <vxe-column type="checkbox" width="50" align="center" fixed="left" />
        <vxe-column
          :title="t('student.fields.studentName')"
          field="studentName"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
          fixed="left"
        />
        <vxe-column
          :title="t('student.fields.recruitType')"
          field="recruitType"
          align="center"
          show-header-overflow
          show-overflow
          min-width="120"
        />
        <vxe-column
          :title="t('student.fields.phone')"
          field="phone"
          align="center"
          show-header-overflow
          show-overflow
          min-width="120"
        />
        <vxe-column
          :title="t('student.fields.batchId')"
          field="batchId"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        >
          <template #default="scope">
            {{ batchOptions.find((item) => item.id === scope.row.batchId)?.batchName }}
          </template>
        </vxe-column>
        <vxe-column
          :title="t('student.fields.interviewScore')"
          field="interviewScore"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.interviewStatus')"
          field="interviewStatus"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.interviewGroupId')"
          field="groupName"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.interviewSelected')"
          field="interviewSelected"
          align="center"
          show-header-overflow
          show-overflow
          min-width="130"
        >
          <template #default="scope">
            {{ scope.row.interviewSelected ? t('common.yes') : t('common.no') }}
          </template>
        </vxe-column>
        <vxe-column
          :title="t('student.fields.interviewTime')"
          field="interviewTime"
          align="center"
          show-header-overflow
          show-overflow
          min-width="120"
        />
        <vxe-column
          :title="t('student.fields.interviewSlotTime')"
          field="interviewSlotTime"
          align="center"
          show-header-overflow
          show-overflow
          min-width="140"
        />
        <vxe-column
          :title="t('student.fields.birthdate')"
          field="birthdate"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
          :formatter="vxeDateFormatter2"
        />
        <vxe-column
          :title="t('student.fields.gender')"
          field="gender"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.politicalStatus')"
          field="politicalStatus"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.ethnic')"
          field="ethnic"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.identityNumber')"
          field="identityNumber"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.contactAddress')"
          field="contactAddress"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.email')"
          field="email"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.university')"
          field="university"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.is985')"
          field="is985"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
          :formatter="vxeBooleanFormatter"
        />
        <vxe-column
          :title="t('student.fields.is211')"
          field="is211"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
          :formatter="vxeBooleanFormatter"
        />
        <vxe-column
          :title="t('student.fields.isFirstClass')"
          field="isFirstClass"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
          :formatter="vxeBooleanFormatter"
        />
        <vxe-column
          :title="t('student.fields.studyMajor')"
          field="studyMajor"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.applyMajor')"
          field="applyMajor"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.majorRank')"
          field="majorRank"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.majorTotal')"
          field="majorTotal"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.classRank')"
          field="classRank"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.classTotal')"
          field="classTotal"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.cet4Score')"
          field="cet4Score"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.cet6Score')"
          field="cet6Score"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        />
        <vxe-column
          :title="t('student.fields.attachment')"
          field="attachment"
          align="center"
          show-header-overflow
          show-overflow
          min-width="100"
        >
          <template #default="scope">
            <FileObjectDownload :file-json="scope.row.attachment" />
          </template>
        </vxe-column>
        <vxe-column
          :title="t('common.operate')"
          field="operator"
          align="center"
          fixed="right"
          width="210"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleChangeInterview(scope.row)"
              v-hasPermi="['recruit:student:update']"
              :disabled="
                !(
                  scope.row.interviewQuality === '同意面试' &&
                  scope.row.interviewStatus === '未面试'
                )
              "
            >
              {{ t('student.index.changeInterview') }}
            </el-button>
            <el-button
              link
              type="primary"
              @click="handleSetInterviewResult(scope.row)"
              v-hasPermi="['recruit:student:update']"
              :disabled="!scope.row.interviewScore"
            >
              {{ t('student.index.setResult') }}
            </el-button>
          </template>
        </vxe-column>
      </vxe-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
  </Dialog>

  <!-- 修改面试时间 -->
  <ChangeStudentInterviewSlot ref="changeSlotRef" @success="getList" />

  <!-- 批量设置面试结果弹窗 -->
  <Dialog
    :title="batchInterviewMode ? t('student.index.setResultBatch') : t('student.index.setResult')"
    v-model="dialogResultVisible"
    width="400"
    :fullscreen="false"
  >
    <el-alert
      v-if="batchInterviewMode"
      class="!mb-[10px]"
      :title="t('student.index.batchSelectTips', { num: selectListObject.length })"
      type="success"
      :closable="false"
    />
    <el-form>
      <el-form-item :label="t('student.fields.interviewStatus')">
        <el-select
          v-model="interviewStatus"
          :placeholder="t('common.selectTextPlaceholder') + t('student.fields.interviewStatus')"
        >
          <el-option :label="t('student.index.isPassed')" value="面试合格" />
          <el-option :label="t('student.index.isIndeterminate')" value="面试合格（候补）" />
          <el-option :label="t('student.index.isFail')" value="面试不合格" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{
        t('common.ok')
      }}</el-button>
      <el-button @click="dialogResultVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import {
  RecruitStudentGroupingListRespVO,
  StudentApi,
  StudentVO
} from '@/api/recruit/recruitstudent'
import type { VxeTableInstance, VxeTablePropTypes, VxeToolbarInstance } from 'vxe-table'
import { useAppStore } from '@/store/modules/app'
import { BatchApi, BatchVO } from '@/api/recruit/batch'
import { InterviewVO } from '@/api/recruit/interview'
import { InterviewGroupApi, InterviewGroupSimpleListRespVO } from '@/api/recruit/interviewgroup'
import { vxeDateFormatter, vxeDateFormatter2 } from '@/utils/formatTime'
import ChangeStudentInterviewSlot from '@/views/recruit/recruitstudent/components/ChangeStudentInterviewSlot.vue'
import FileObjectDownload from '@/components/FileObjectDownload/index.vue'
import { vxeBooleanFormatter } from '@/utils/formatter'

/** 指定面试下的学生列表 */
defineOptions({ name: 'RecruitStudentListInInterview' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const toolbarRef = ref<VxeToolbarInstance>()
const tableRef = ref<VxeTableInstance>()

const loading = ref(true) // 列表的加载中
const list = ref<RecruitStudentGroupingListRespVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const dialogVisible = ref(false)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  advanced: undefined,
  accountId: undefined,
  studentName: undefined,
  recruitType: undefined,
  phone: undefined,
  batchId: undefined,
  recruitStatus: undefined,
  recruitTime: [],
  interviewQuality: undefined,
  interviewSelected: undefined,
  interviewDate: [],
  interviewTime: undefined,
  interviewStatus: undefined,
  interviewId: undefined,
  interviewGroupId: undefined,
  interviewSlotId: undefined,
  interviewSlotTime: undefined,
  interviewScore: undefined,
  chioceStatus: undefined,
  chioceMentorId: undefined,
  birthdate: [],
  gender: undefined,
  politicalStatus: undefined,
  ethnic: undefined,
  identityNumber: undefined,
  contactAddress: undefined,
  email: undefined,
  university: undefined,
  is985: undefined,
  is211: undefined,
  isFirstClass: undefined,
  studyMajor: undefined,
  applyMajor: undefined,
  majorRank: undefined,
  majorTotal: undefined,
  classRank: undefined,
  classTotal: undefined,
  cet4Score: undefined,
  cet6Score: undefined,
  attachment: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const emits = defineEmits<{
  (e: 'next', value: StudentVO[]): void
}>()

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

const selectListObject = ref<StudentVO[]>([])

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await StudentApi.getStudentGroupingList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  ;(queryParams as any).advanced = undefined
  queryParams.batchId = currentInterview.value?.batchId as any
  queryParams.interviewId = currentInterview.value?.id as any
  handleQuery()
}

const collectSelect = () => {
  selectListObject.value = [
    ...(tableRef.value?.getCheckboxRecords() ?? []),
    ...(tableRef.value?.getCheckboxReserveRecords() ?? [])
  ] as StudentVO[]
}

const formLoading = ref(false)

const batchOptions = ref<BatchVO[]>([])
const getBatchSelectOptions = async () => {
  batchOptions.value = await BatchApi.getSelectList()
}

const currentInterview = ref<InterviewVO>()

const groups = ref<InterviewGroupSimpleListRespVO[]>([])

// 面试管理-设置分组 新增第一步 弹出学生列表
const open = async (interview: InterviewVO) => {
  currentInterview.value = interview
  dialogVisible.value = true
  await nextTick()
  resetQuery()
  groups.value = await InterviewGroupApi.simpleList(currentInterview.value.id)
}

const changeSlotRef = ref<InstanceType<typeof ChangeStudentInterviewSlot>>()
// 修改面试时间
const handleChangeInterview = async (row: StudentVO) => {
  changeSlotRef.value?.open(row.id)
}

const handleNext = () => {
  if (selectListObject.value.length === 0) {
    message.error(t('student.groupSelect.noData'))
    return
  }
  emits('next', selectListObject.value)
  dialogVisible.value = false
  selectListObject.value = []
}

const batchInterviewMode = ref(false)
const dialogResultVisible = ref(false)
const interviewStatus = ref('')
const currentRow = ref<StudentVO>()

const handleSetInterviewResult = (row: StudentVO) => {
  batchInterviewMode.value = false
  currentRow.value = row
  interviewStatus.value = (row.interviewStatus ?? '') === '未面试' ? '' : row.interviewStatus
  dialogResultVisible.value = true
}

const handleBatchSetInterviewResult = () => {
  batchInterviewMode.value = true
  interviewStatus.value = ''
  dialogResultVisible.value = true
}

const submitForm = async () => {
  if (interviewStatus.value === '') {
    message.error(t('common.selectTextPlaceholder') + t('student.fields.interviewStatus'))
    return
  }
  formLoading.value = true
  try {
    let ids
    if (batchInterviewMode.value) {
      ids = selectListObject.value.map((item) => item.id)
    } else {
      ids = [currentRow.value?.id]
    }

    await StudentApi.batchSetInterviewResult({
      interviewStatus: interviewStatus.value,
      recruitStudentIds: ids
    })
    message.success(t('common.operSuccess'))
    dialogResultVisible.value = false
    getList()
  } catch {
  } finally {
    formLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  // 查询所有计划
  await getBatchSelectOptions()
})

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
:deep(.vxe-cell--checkbox.is--disabled) {
  .vxe-table-icon-checkbox-unchecked:before {
    content: '\e8c4';
  }
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 10px !important;
}

:deep(.vxe-cell .el-button + .el-button) {
  margin-left: 0;
}
</style>
